package xx.rabbitmq.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
;

@Slf4j
@RestController
public class MqController {

    /**
     * 使用RabbitTemplate,这提供了接收/发送等等方法
     */
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * Header Exchange
     * @param msg
     */
    @GetMapping("/creditBank")
    public void creditBank(String msg){
        log.info("credit.bank send message: "+msg);
        Map<String,Object> head = new HashMap<>();
        head.put("type", "cash");
        rabbitTemplate.convertAndSend("creditBankExchange", "credit.bank", getHeaderMessage(head, msg));
    }

    /**
     * Header Exchange
     * @param msg
     */
    @GetMapping("/creditFinance")
    public void creditFinance( String msg){
        log.info("credit.finance send message: "+msg);
        Map<String,Object> head = new HashMap<>();
        head.put("type", "cash");
        head.put("aging", "fast");
        rabbitTemplate.convertAndSend("creditFinanceExchange", "credit.finance", getHeaderMessage(head, msg));
    }



    public static Message getHeaderMessage(Map<String, Object> head, String msg) {
        MessageProperties messageProperties = new MessageProperties();
        head.forEach((key,value)->{
            messageProperties.setHeader(key,value);
        });
        Message message = new Message(msg.getBytes(), messageProperties);
        return message;
    }


    public static Map<String, Object> getMessage(String messageData) {
        String messageId = String.valueOf(UUID.randomUUID());
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        return map;
    }
}
